package com.xhapi.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.xhapi.annotation.AuthAccess;
import com.xhapi.pojo.entity.ApiResult;
import com.xhapi.service.OCRService;
import com.xhapi.utils.ApiResultHandler;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    private final OCRService ocrService;
    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    /*
     * 这个用的合合信息的文字识别，不支持手写字
     * */
    @PostMapping("/uploadNormal")
    public ApiResult uploadForNormal(MultipartFile file) throws Exception {
        try {
            String text = ocrService.picToText(file.getBytes());
            upload(file);
            return ApiResultHandler.success(text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /*
     * 这个用的星火的手写字文字识别
     * */
    @PostMapping("/uploadHandWrite")
    public ApiResult uploadForHandWrite(MultipartFile file) {
        try {
            String path = upload(file);
            String text = ocrService.picToTextByHandWrite(path);
            return ApiResultHandler.success(text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     *
     * */
    private static String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileNameUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);//不存在创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;//存在命名
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);//存储本地
        String url = "http://localhost:8081/file/download/" + originalFilename;
        return ROOT_PATH + File.separator + originalFilename;
    }


    @AuthAccess
    @GetMapping("/download/{fileName}")
    public ApiResult download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        System.out.println(filePath);
        if (!FileUtil.exist(filePath)) {
            return ApiResultHandler.success("无法访问");
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        return ApiResultHandler.success();
    }
}
